package com.seagox.desk.config;

import java.util.UUID;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.seagox.desk.remote.entity.BaseUser;
import com.seagox.desk.remote.mapper.UserMapper;

@Component
public class EventListenner {
	
	private static final Logger logger = LoggerFactory.getLogger(EventListenner.class);
	
    @Resource
    private ClientCache clientCache;
    
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    
    @Autowired
    private UserMapper userMapper;

    /**
     * 客户端连接
     *
     * @param client
     */
    @OnConnect
    public void onConnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        if(!StringUtils.isEmpty(userId)) {
        	UUID sessionId = client.getSessionId();
            clientCache.saveClient(userId, sessionId, client);
            logger.info("建立连接:" + userId);
            LambdaQueryWrapper<BaseUser> updateWrapper = new LambdaQueryWrapper<>();
            updateWrapper.eq(BaseUser::getIdentifyCode, userId);
            BaseUser user = new BaseUser();
            user.setStatus(1);
            userMapper.update(user, updateWrapper);
        }
    }

    /**
     * 客户端断开
     *
     * @param client
     */
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        clientCache.deleteSessionClient(userId, client.getSessionId());
        client.disconnect();
        logger.info("关闭连接:" + userId);
        LambdaQueryWrapper<BaseUser> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(BaseUser::getIdentifyCode, userId);
        BaseUser user = new BaseUser();
        user.setStatus(0);
        userMapper.update(user, updateWrapper);
    }
	
	@OnEvent("message")
	public void message(SocketIOClient client, AckRequest request, JSONObject data) {
		redisTemplate.convertAndSend("message", data.toJSONString());
	}
    
}

